import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/common_model/resp_user_model.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/check_for_updates.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/utils/upgrade_notice_dialog.dart';
import 'package:oktoast/oktoast.dart';

import '../../utils/account_been_frozen_dialog.dart';
import '../../utils/suspend_account_dialog.dart';

class LoginController extends GetxController {
  static const boardingPassToken = "boarding_pass_token";
  final GlobalController globalController = Get.find();

  final loginEnable = true.obs;
  final showCodeErrorText = false.obs;
  final showPasswordErrorText = false.obs;
  final isRead = false.obs;
  final current = 'phone'.obs;
  final userTel = ''.obs;
  final account = ''.obs;
  String? password;
  String? code;
  int? smsId;
  @override
  void onInit() {
    super.onInit();
    HiCache.getInstance().remove(LoginController.boardingPassToken);
    //  globalController.getStaticData();
    userTel.value = '';
    fetchVersionInfo().then((res) {
      chech_updata(res: res, context: Get.context!);
    });
  }

  void onValueChanged(val, type) {
    if (type == 'account') {
      account.value = val;
    }
    if (type == 'password') {
      password = val;
    }
    if (type == 'userTel') {
      userTel.value = val;
    }
    if (type == 'code') {
      code = val;
    }
    if (type == 'smsId') {
      smsId = val;
    }

    loginEnable(
      current.value == 'password'
          ? (account.value.isNotEmpty && password != null)
          : (userTel.value.isNotEmpty && code != null),
    );
  }

  void submit() async {
    if (current.value == 'password') {
      http.netFetch<RespUserModel>(
        ApiUrl.loginByPwd,
        method: Method.post,
        params: {'userAccount': account.value, 'pwd': password},
        success: (result) {
          if (result.data?.code == 30000) {
            //注销成功后的限制期限内
            _cancelLogOff(
              cancelTime: result.data!.nextRegisterTime.toString(),
              phone: account.value,
              time: result.data!.registerLimitDays.toString(),
            );
          } else if (result.data?.code == 20000) {
            //注销中
            _cancelLogOff(
              cancelTime: result.data!.cancelTime.toString(),
              phone: account.value,
            );
          } else if (result.data?.code == 10000) {
            //冻结
            _userFreezed(
              result.data!.freezeTime.toString(),
              result.data!.freezeReason.toString(),
            );
          } else if (result.data?.token != null) {
            // consoleLog('登录成功！tolen = ${result.data?.token}');
            saveBoardPassToken(result.data?.token);
            storeToken(result.data!.token);
            showToast('登录成功！');
            globalController.getUserInfo();
            globalController.getStaticData();
            Get.offAllNamed(MainPage.path);
          }
        },
      );
    } else {
      http.netFetch<RespUserModel>(
        ApiUrl.loginBySms,
        method: Method.post,
        params: {'userTel': userTel.value, 'code': code, 'smsId': smsId},
        success: (result) {
          if (result.data?.code == 30000) {
            //注销成功后的限制期限内
            _cancelLogOff(
              cancelTime: result.data!.nextRegisterTime.toString(),
              phone: account.value,
              time: result.data!.registerLimitDays.toString(),
            );
          } else if (result.data?.code == 20000) {
            //注销
            _cancelLogOff(
              cancelTime: result.data!.cancelTime.toString(),
              phone: userTel.value.toString(),
            );
          } else if (result.data?.code == 10000) {
            //冻结
            _userFreezed(
              result.data!.freezeTime.toString(),
              result.data!.freezeReason.toString(),
            );
          } else if (result.data?.token != null) {
            // consoleLog('登录成功！tolen = ${result.data?.token}');
            saveBoardPassToken(result.data?.token);
            showToast('登录成功！');
            storeToken(result.data!.token);
            globalController.getUserInfo();
            globalController.getStaticData();
            Get.offAllNamed(MainPage.path);
          }
        },
      );
    }
  }

  _userFreezed(freezeTime, freezeReason) {
    return showConfirmDialog(
      context: Get.context!,
      fontSize: 16,
      closeButton: true,
      message: '账号已被冻结，请联系客服',
      type: 'account_freeze',
      messages: ['解冻时间：$freezeTime', '冻结原因:$freezeReason'],
      actions: [ActionModel(width: 204, label: '我知道了', onPressed: () {})],
    );
  }

  _cancelLogOff({required String cancelTime, required String phone, time}) {
    return showConfirmDialog(
      context: Get.context!,
      message: time == null ? '账号申请注销中' : '账号注销未超过$time天',
      children: [
        RichText(
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          text: TextSpan(
            children: <TextSpan>[
              TextSpan(
                text: '可在',
                style: TextStyle(
                  color: AppColors.fontColorGray99,
                  fontSize: 12.px,
                ),
              ),
              TextSpan(
                text: cancelTime,
                style: TextStyle(
                  color: AppColors.fontColorSearch,
                  fontSize: 12.px,
                ),
              ),
              TextSpan(
                text: time == null ? '前随时取消注销' : '后再次进行注册',
                style: TextStyle(
                  color: AppColors.fontColorGray99,
                  fontSize: 12.px,
                ),
              ),
            ],
          ),
        ),
      ],

      actions:
          time == null
              ? [
                ActionModel(
                  label: '关闭',
                  onPressed: () {},
                  colorStart: AppColors.backgroundColorGreyF8,
                  colorEnd: AppColors.backgroundColorGreyF8,
                  fontColor: AppColors.fontColor,
                ),
                ActionModel(
                  label: '取消注销',
                  colorStart: AppColors.fontColorRed2,
                  colorEnd: AppColors.fontColorRed2,
                  fontColor: AppColors.fontColor,
                  onPressed: () {
                    http.netFetch(
                      ApiUrl.cancelLogOff,
                      method: Method.post,
                      params: {'userAccount': phone},
                      success: (data) {
                        if (data.code == 200) {
                          showToast("取消注销成功");
                        }
                      },
                    );
                  },
                ),
              ]
              : [
                ActionModel(
                  label: '关闭',
                  onPressed: () {},
                  colorStart: AppColors.backgroundColorGreyF8,
                  colorEnd: AppColors.backgroundColorGreyF8,
                  fontColor: AppColors.fontColor,
                ),
              ],
    );
  }

  void onReadChanged(value) {
    isRead(value);
  }

  void onTypeChanged(String value) {
    current(value);
    // account = null;
    // password = null;
  }

  void saveBoardPassToken(token) {
    HiCache.getInstance().setString(boardingPassToken, token);
  }
}
